// websocketService.js  
  
class WebSocketService {  
    constructor(url) {  
      this.socket = null;  
      this.url = url;  
      this.handlers = {  
        onopen: null,  
        onmessage: null,  
        onerror: null,  
        onclose: null  
      };  
    }  
    
    connect() {

      if (this.socket && this.socket.readyState === WebSocket.OPEN) {  
        console.log('WebSocket 已经连接');  
        return;  
      }

    
      this.socket = new WebSocket(this.url);  
    
      this.socket.onopen = (event) => {  
        console.log('WebSocket 连接已打开');  
        if (this.handlers.onopen) {  
          this.handlers.onopen(event);  
        }  
      };  
    
      this.socket.onmessage = (event) => {  
        console.log('从服务器接收到消息:', event.data);  
        if (this.handlers.onmessage) {  
          this.handlers.onmessage(event);  
        }  
      };  
    
      this.socket.onerror = (error) => {  
        console.error('WebSocket 发生错误:', error);  
        if (this.handlers.onerror) {  
          this.handlers.onerror(error);  
        }  
      };  
    
      this.socket.onclose = (event) => {  
        console.log('WebSocket 连接已关闭'); 
        setTimeout(() => {
          this.reconnect(); // 尝试重连
        },2000)
        if (this.handlers.onclose) {  
          this.handlers.onclose(event);  
        }  
      };  
    }  
    
    send(message) {  
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {  
        this.socket.send(message);  
      } else {  
        console.error('WebSocket 连接未打开，无法发送消息');  
      }  
    }  
    
    on(eventName, handler) {  
      if (this.handlers[eventName]) {  
        this.handlers[eventName] = handler;  
      } else {  
        console.error(`未知的 WebSocket 事件: ${eventName}`);  
      }  
    }  
    
    close() {  
      if (this.socket) {  
        this.socket.close();  
        this.socket = null;  
      }  
    }

    reconnect() {  
      if (this.socket && this.socket.readyState === WebSocket.OPEN) { 
          console.log('已经连接，无需重连');
          return;  
      }

      // 设置一个延迟来避免频繁重连  
      const delay = this.getReconnectDelay();  
        setTimeout(() => {  
            this.connect(); // 尝试连接  
        }, delay);  
    }  

    getReconnectDelay() {
          return 500; // 返回计算的延迟时间  
    }  
  }  
    
  export default WebSocketService;